/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.tln.sys.role.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javacommon.base.BaseRestSpringController;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.apache.shiro.crypto.hash.Sha256Hash;

import com.fins.gt.server.GridServerHandler;
import com.tln.sys.role.model.Role;
import com.tln.sys.role.service.RoleService;
import com.xjj.core.modules.orm.Page;

/**
 * Web MVC controller that handles operations related to managing users, such as editing them and deleting them. 
 */
@Controller
@RequestMapping("/sys/role/**")
public class RolesController extends BaseRestSpringController<Role,java.lang.Long>{
	
	private static final Logger logger = LoggerFactory.getLogger(RolesController.class);

    private EditRoleValidator editRoleValidator = new EditRoleValidator();
    
    private Role role;
    
    private Page<Role> page = new Page<Role>(20);//每页5条记录

    private RoleService roleService;

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
    
    // /sys/Role/
  //默认方法
	@Override
	public String index(HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute Role entity,Model model) {
		logger.info("index............");
		return "/sys/role/roleList";
	}
	
	//  /sys/Role/list
	@Override
	public String list(HttpServletRequest request,HttpServletResponse response,
			Role Role,Model model){
		logger.info("***************list********************");
		Map map = new HashMap();
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		Map param = gridServerHandler.getParameters() ;
		logger.info("传递参数param---- "+param);
		JsonNode parametersJsonNode = gridServerHandler.getParametersJsonNode();
		logger.info("传递参数param---- "+parametersJsonNode);
		//过滤
		List sortInfoList = gridServerHandler.getSortInfo();
		logger.info("sortInfoList---"+sortInfoList.size());
		List list = gridServerHandler.getFilterInfo();
		logger.info("list--- "+list);
		//获取总记录数
		int pageNo = gridServerHandler.getPageNum();//第几页
		//logger.info("pageNo------------ "+pageNo);
		int pageSize = gridServerHandler.getPageSize();//每页多少条记录
		//logger.info("pageSize------------ "+pageSize);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = this.roleService.getAllRoleByHql(map, pageNo, pageSize);
		logger.info("page size== "+page.getTotalCount());
		//jsonAwareCollect.add("advertisePosition");
		//page.setResult(result);
		gridServerHandler.setTotalRowNum(page.getTotalCount());
		gridServerHandler.setData(page.getResult());
		//绕过jsp 、freemarker 进行，非常的酷
		renderJson(response, gridServerHandler.getLoadResponseText());
		
		return null;
	}
	
	
	@RequestMapping(value="/doSave")
	public String doSave(HttpServletRequest request,HttpServletResponse response) {
		logger.info("doSave............");
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		//取得新增的数据集合, 每条数据记录在 map 里
		//List insertedRecords = gridServerHandler.getInsertedRecords();
		JsonNode insertJsonNode = gridServerHandler.getInsertedJsonNodeRecords();
		Iterator<JsonNode> insertNodes = insertJsonNode.getElements(); 
		ObjectMapper mapper = new ObjectMapper(); 
		while (insertNodes.hasNext()) {  
			logger.info("保存操作.............");
			Role entity = new Role();
            JsonNode node = insertNodes.next();
            //String icon = node.get("icon").getTextValue();
            //entity.setIcon(icon);
            try {
            	entity = mapper.readValue(node, Role.class);
            	//Role Role = new Role();
            	//entity.setRolename(Rolename);
            	//entity.setEmail(email);
            	//entity.setPassword( new Sha256Hash(entity.getPassword()).toHex() );
                
				logger.info("getName-icon- "+entity.getName()+",name== "+entity.getDescription());
				logger.info("getPermissions-icon- "+entity.getPermissions());
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
            this.roleService.saveRole(entity);
        }
		
		JsonNode updateJsonNode = gridServerHandler.getUpdatedJsonNodeRecords();
		Iterator<JsonNode> updateNodes = updateJsonNode.getElements(); 
		
		while (updateNodes.hasNext()) {  
			logger.info("更新操作.............");
			
			//ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally  
            JsonNode node = updateNodes.next();
            try {
				role = mapper.readValue(node, Role.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//Role Role = new Role();
	        //Role.setRolename(Rolename);
	        //Role.setEmail(email);
	        //Role.setPassword( new Sha256Hash(Role.getPassword()).toHex() );
	        
			this.roleService.saveRole(role);
        }
		
		JsonNode deleteJsonNode = gridServerHandler.getDeletedJsonNodeRecords();
		Iterator<JsonNode> deleteNodes = deleteJsonNode.getElements(); 
		
		while (deleteNodes.hasNext()) {  
			logger.info("删除操作.............");
            JsonNode node = deleteNodes.next();
            Long id = node.get("id").getLongValue();
            
            this.roleService.deleteRole(id);
        }
		
		//设置该次操作是否成功.
		gridServerHandler.setSuccess(true);
		
		//如果操作不成功 你也可以自定义一些异常信息发送给客户端.
		//gridServerHandler.setSuccess(false);
		
		//向客户端输出json字符串.
		renderJson(response,gridServerHandler.getSaveResponseText());
		logger.info("SUCCESS............");
		return null;//new ModelAndView("/company/list");
	}

    @RequestMapping("/manageRoles")
    @RequiresPermissions("Role:manage")
    public void manageRoles(Model model) {
        model.addAttribute("Roles", roleService.getAllRoles());
    }

    @RequestMapping(value="/editRole",method= RequestMethod.GET)
    @RequiresPermissions("Role:edit")
    public String showEditRoleForm(Model model, @RequestParam Long roleId, 
    		@ModelAttribute EditRoleCommand command) {
    	
        Role role = roleService.getRole( roleId );
        //command.setRoleId(roleId);
        //command.setRolename(Role.getRolename());
        //command.setEmail(Role.getEmail());
        return "/sys/role/editRole";
    }

    @RequestMapping(value="/editRole",method= RequestMethod.POST)
    @RequiresPermissions("Role:edit")
    public String editRole(Model model, @RequestParam Long RoleId, 
    		@ModelAttribute EditRoleCommand command, BindingResult errors) {
    	logger.info("更新操作吗。。。。。。。。。。。。。。。。。。。。");
        editRoleValidator.validate( command, errors );

        if( errors.hasErrors() ) {
            return "editRole";
        }

        Role role = roleService.getRole( RoleId );
        command.updateRole( role );

        roleService.updateRole( role );

        return "redirect:/sys/Role/manageRoles";
    }

    @RequestMapping("/deleteRole")
    @RequiresPermissions("Role:delete")
    public String deleteRole(@RequestParam Long RoleId) {
        Assert.isTrue( RoleId != 1, "Cannot delete admin Role" );
        roleService.deleteRole( RoleId );
        return "redirect:/sys/Role/manageRoles";
    }

}
